package com.ruubypay.biz.mvc.workflow.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruubypay.biz.mvc.workflow.model.request.ProcessDefined;
import com.ruubypay.biz.mvc.workflow.service.ProcessService;
import com.ruubypay.biz.mvc.workflow.service.impl.ProcessServiceImpl;
import com.ruubypay.biz.utils.file.FileDownload;
import com.ruubypay.biz.utils.file.FileZip;
import com.ruubypay.biz.utils.file.PathUtil;
import com.ruubypay.web.common.code.ResultCode;
import com.ruubypay.web.common.code.ResultEntity;
import com.ruubypay.web.common.page.DataGrid;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 流程管理 控制层
 * @author chenhaiyang
 */
@Controller
@RequestMapping(value="/workflow/process/")
public class ProcessController {

    private static Logger logger = LoggerFactory.getLogger(ProcessController.class);

    @Resource
    private ProcessService processService;
    /**
     * 列表页跳转
     * @return 返回url
     */
    @RequestMapping(value = "/list" , method = RequestMethod.GET)
    public String listModels() {
        return "views/process/process_list";
    }

    /**
     * 跳转到预览xml图页面
     * @return 返回视图
     */
    @RequestMapping(value = "/viewxml" , method = RequestMethod.GET)
    public ModelAndView viewxml(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("views/model/model_xmlview");

        String deploymentId=request.getParameter("deploymentId");
        try {
            String code = processService.viewXmlFromDeploymentId(deploymentId);
            mv.addObject("code",code);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
        return mv;
    }

    /**
     * 跳转到预览png图页面
     * @return 返回视图
     */
    @RequestMapping(value = "/viewpng" , method = RequestMethod.GET)
    public ModelAndView viewpng(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("views/model/model_pngview");
        String deploymentId=request.getParameter("deploymentId");
        try {
            String image = processService.viewPngFromDeploymentId(deploymentId);
            mv.addObject("imgSrc",image);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
        return mv;
    }

    /**
     * 导入流程
     * @return 返回视图
     */
    @RequestMapping(value = "/uploadprocess" , method = RequestMethod.GET)
    public ModelAndView uploadprocess(){
        return new ModelAndView("views/process/process_upload");
    }

    /**
     * 获取模型列表
     * @return 模型
     */
    @ResponseBody
    @RequestMapping(value="/list",method = RequestMethod.POST)
    public String list(HttpServletRequest request) {

        Map<String, Object> paramMap = new HashMap<>(16);
        paramMap.put("key",request.getParameter("key"));
        Integer pageNumber = ServletRequestUtils.getIntParameter(request,"pageNumber",1);
        Integer pageSize = ServletRequestUtils.getIntParameter(request,"pageSize",10);

        DataGrid modelPage = null;
        try {
            modelPage = processService.listDataProcesses(paramMap,pageNumber,pageSize);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return JSON.toJSONString(modelPage);
    }

    /**
     * 删除流程
     * @param request requrst请求类
     * @return 返回删除结果
     */
    @ResponseBody
    @RequestMapping(value="/delete",method = RequestMethod.GET)
    public String delete(HttpServletRequest request){
        ResultEntity<String> resultEntity = new ResultEntity<>(ResultCode.COMMON_SUCCESS);
        String idArray = request.getParameter("idArray");
        if (StringUtils.isNotBlank(idArray)) {
            try {
                int l = processService.deleteProcessService(idArray);
                resultEntity.setResData(l + "");
            } catch (Exception e) {
                resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_SERVER_DATABASE);
                logger.error(e.getMessage(),e);
            }
            return JSONObject.toJSONString(resultEntity);
        }
        resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_CLIENT_PARAMETER_NUll);
        return JSONObject.toJSONString(resultEntity);
    }

    /**
     * 流程的挂起或者激活
     * @param processDefined 流程定义信息
     * @return 返回挂起或者激活的结果
     */
    @ResponseBody
    @RequestMapping(value="/onoff",method = RequestMethod.POST)
    public String onoff(ProcessDefined processDefined){

        ResultEntity<String> resultEntity = new ResultEntity<>(ResultCode.COMMON_SUCCESS);
        if (StringUtils.isNotBlank(processDefined.getId())&&
                Arrays.asList(1,2).contains(processDefined.getIsSuspended())) {
            try {
                processService.suspendedOrNo(processDefined);
            } catch (Exception e) {
                resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_SERVER_DATABASE);
                logger.error(e.getMessage(),e);
            }
            return JSONObject.toJSONString(resultEntity);
        }
        resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_CLIENT_PARAMETER_NUll);
        return JSONObject.toJSONString(resultEntity);
    }

    /**
     * 打包下载流程资源文件
     * @param request 请求
     * @param response 响应
     */
    @RequestMapping(value="/download",method = RequestMethod.GET)
    public void download(HttpServletRequest request, HttpServletResponse response){
        String deploymentId = request.getParameter("deploymentId");
        if (StringUtils.isNotBlank(deploymentId)) {
            try {
                processService.createzips(deploymentId);
                String filePath =ProcessServiceImpl.getFilePath();
                String zipPath = filePath+".zip";
                String fileName ="activitiFile.zip";
                /*生成的全部代码压缩成zip文件*/
                if(FileZip.zip(PathUtil.getClasspath()+filePath, PathUtil.getClasspath()+zipPath)){
			        /*下载代码*/
                    FileDownload.fileDownload(response, PathUtil.getClasspath()+zipPath, fileName);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        }
    }

    /**
     * 映射为模型
     * @param processDefined 流程定义对象
     */
    @ResponseBody
    @RequestMapping(value="/addmodel",method = RequestMethod.POST)
    public String addmodel(ProcessDefined processDefined){
        ResultEntity<String> resultEntity = new ResultEntity<>(ResultCode.COMMON_SUCCESS);
        if (StringUtils.isNotBlank(processDefined.getId())) {
            try {
                processService.addModel(processDefined);
            } catch (Exception e) {
                resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_SERVER_DATABASE);
                logger.error(e.getMessage(),e);
            }
            return JSONObject.toJSONString(resultEntity);
        }
        resultEntity.setCodeMsg(ResultCode.COMMON_ERROR_CLIENT_PARAMETER_NUll);
        return JSONObject.toJSONString(resultEntity);
    }

    /**
     * 资源文件上传（工作流文件）
     * @param file 文件
     */
    @RequestMapping(value="/upload",method = RequestMethod.POST)
    public ModelAndView upload(@RequestParam(value="zip",required=false) MultipartFile file){

        ModelAndView mv = new ModelAndView("views/process/upload_result");
        try {
            processService.uploadZips(file.getInputStream());
            mv.addObject("msg","导入流程成功！");
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
            mv.addObject("msg",",导入流程失败！文件资源不符合流程标准( 或缺少 xml or png )");
        }
        return mv;
    }
}
